import _ from 'lodash';
import { uid } from '@teld/q-components';
import { toRaw } from 'vue';
import crossWindowMessenger from './crossWindowMessenger.js';

const toolNewConversation = {
  title: '新会话',
  script: " eventService.eventBus._emit('handleClearCurChatDirect')",
  iconhighlight: 1,
  icon: `<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1.44531 5.11868C1.44531 3.65375 2.63287 2.46619 4.0978 2.46619H15.9028C17.3678 2.46619 18.5553 3.65375 18.5553 5.11868V13.9544C18.5553 15.4193 17.3678 16.6069 15.9028 16.6069H10.5973C10.2044 16.6069 9.81658 16.6957 9.46286 16.8668L6.86737 18.1221C6.33787 18.3782 5.72281 17.9924 5.72281 17.4043V17.4043C5.72281 16.9639 5.36581 16.6069 4.92543 16.6069H3.58406C2.40286 16.6069 1.44531 15.6493 1.44531 14.4681V5.11868Z" stroke="currentColor" stroke-width="1.67" stroke-linecap="round"/>
<line x1="7.68314" y1="9.61764" x2="12.3168" y2="9.61764" stroke="currentColor" stroke-width="1.67" stroke-linecap="round"/>
<line x1="9.84762" y1="12.1217" x2="9.84762" y2="7.48798" stroke="currentColor" stroke-width="1.67" stroke-linecap="round"/>
</svg>
`,
};

export const TAI_MESSAGE = {
  CONF_AGENT: 'CONF_AGENT',
  SYNC_VARIABLES: 'SYNC_VARIABLES',

  TAI_TOOL: 'TAI_TOOL',
  ACK_TAI_QUESTION: 'ACK_TAI_QUESTION',
};
let isReady = false;
export const ACK_MAPPING = {
  ACK: _.debounce(message => {
    if (false === isReady) {
      console.warn('xiaoTAI尚未就绪:', message);
      return;
    }
    if (message.payload) {
      message.payload = toRaw(message.payload);
    }
    console.log('xiaoTAI-ACK:', message);
    crossWindowMessenger.send(JSON.parse(JSON.stringify(message)));
  }, 300),
  ACK_TAI_READY(AICompOpts) {
    const {
      variables = {},
      problems = [],
      tools = [],
      description = '',
    } = AICompOpts || {};
    // const variables = AICompOpts?.variables?.reduce((r, variable) => {
    //   r[variable.code] = variable.mockData;
    //   return r;
    // }, {});

    let _sysPrompt = AICompOpts?.sysPrompt;
    try {
      _sysPrompt = _.template(AICompOpts?.sysPrompt)(variables);
    } catch (error) {}

    const openingStatement = _.template(AICompOpts?.openingStatement, {
      // interpolate: /{{([\s\S]+?)}}/g,
      interpolate: /[{\[]{2}([\s\S]+?)[}\]]{2}/g, /** {{name}} [[name]] */
    })(variables);

    const defaultMessages = [
      {
        id: uid(),
        status: 'assistant',
        message:
          openingStatement ||
          '你好，我是小特AI，我可以帮助你进行页面数据的分析，你可以随时问我问题。',
      },
    ];
    // if (AICompOpts?.openingStatement) {
    //   defaultMessages.push({
    //     id: this.$utils.fascommon.utils.generateKey.guid.guid(),
    //     status: 'assistant',
    //     message: AICompOpts.openingStatement,
    //   });
    // }

    const defaultQA = [];
    if (description) {
      defaultQA.push({
        key: 'description',
        Q: '功能说明',
        A: description,
        icon: `fas dx-icon icon-t-question-circle`,
      });
    }


    let payload = {
      type: 'szzz_znws',
      // name: '低代码AI助手',
      title: '小特AI',
      available: true,
      provider: ['DIFY_ZNWS'],
      isPromptGenerated: false,
      defaultMessages,
      sysPrompt: AICompOpts?.sysPrompt,
      // _sysPrompt,
      // chatHistory: [
      //   {
      //     role: 'system',
      //     content: _sysPrompt,
      //   },
      // ],
      parentId: 'szzz',
      variables: this.flattenVariables(variables, {
        // '功能说明': description,
        _description_: description,
        // '@description': description,
      }),
      // dataContext: variables,
      suggestion: problems?.map(problem => ({
        // category: '预设问题',
        content: problem.question,
      })),
      defaultQA: defaultQA,
      bottomTools: [
        toolNewConversation,
        ...defaultQA?.map((qa, index) => ({
          icon: qa.icon,
          title: qa.Q,
          iconhighlight: 0,
          script: `eventService.eventBus._emit('sendQAMessage', "${qa.key}")`,
        })),
        ...tools?.map(t => ({
          title: t.label,
          icon: t.icon,
          iconhighlight: 0,
          // callback: `TOOL_${t.id}`,
          script: `const messageToSend = {
            type: '${TAI_MESSAGE.TAI_TOOL}',
            payload: { callback: 'TOOL_${t.id}' },
            sender: 'TAI',
          };
          window.parent.postMessage( messageToSend, '*'); `,
        })),
      ],
    };

    let message = {
      type: TAI_MESSAGE.CONF_AGENT,
      payload: payload,
      sender: 'AIComponent',
    };
    isReady = true;
    this.ACK(message);
  },
  ACK_TAI_QUESTION(event) {
    let payload = '';
    let message = {
      type: TAI_MESSAGE.ACK_TAI_QUESTION,
      payload: payload,
      sender: 'AIComponent',
    };
    this.ACK(message);
  },
  flattenVariables(data, base = {}) {
    let variables = {};
    if (_.isArray(data)) {
      variables = data.reduce((r, variable) => {
        r[variable.code] = JSON.stringify(variable.value);
        return r;
      }, base);
    } else {
      variables = _.transform(
        data,
        (r, v, k) => {
          r[k] = JSON.stringify(v);
        },
        base,
      );
    }
    return variables;
  },
  SYNC_VARIABLES(data, base = {}) {
    debugger;
    let variables = this.flattenVariables(data, base);
    let message = {
      type: TAI_MESSAGE.SYNC_VARIABLES,
      payload: { variables },
      sender: 'AIComponent',
    };
    this.ACK(message);
  },
};
